package cn.wellcare.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wellcare.constant.Constants;
import cn.wellcare.entity.SystemResources;
import cn.wellcare.entity.SystemResourcesRoles;
import cn.wellcare.exception.BusinessException;
import cn.wellcare.pojo.ResourceTree;
import cn.wellcare.pojo.ServiceResponse;
import cn.wellcare.service.SystemResourcesRolesService;
import cn.wellcare.service.SystemResourcesService;
import cn.wellcare.utils.HttpJsonResult;
import cn.wellcare.utils.WebUtil;

/**
 * 资源表相关action
 * 
 * @Filename: SystemResources.java
 * @Version: 1.0
 * 
 */
@Controller
@RequestMapping(value = "systemresources")
@Scope("prototype")
public class SystemResourcesController {
	@Resource
	private SystemResourcesRolesService resourcesRolesService;
	@Resource
	private SystemResourcesService resourcesService;
	private List<Integer> resRoleIds = new ArrayList<Integer>();
	private List<SystemResources> allres;
	private byte[] token = new byte[0];

	/**
	 * 默认页面
	 * 
	 * @param dataMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "", method = { RequestMethod.GET })
	public String index(HttpServletRequest request, ModelMap dataMap) throws Exception {
		dataMap.put("pageSize", Constants.DEFAULT_PAGE_SIZE);

		Map<String, Object> queryMap = WebUtil.handlerQueryMap(request);
		dataMap.put("queryMap", queryMap);
		return "system/systemresourceslist";
	}

	/**
	 * gridDatalist数据
	 * 
	 * @param request
	 * @param dataMap
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public List<SystemResources> list(@RequestParam(value = "id", required = true) Integer pid,
			HttpServletRequest request, ModelMap dataMap) {
		ServiceResponse<List<SystemResources>> serviceResult = resourcesService.getByPid(pid);
		if (!serviceResult.getSuccess()) {
			if (Constants.SERVICE_RESULT_CODE_SYSERROR.equals(serviceResult.getMsgCode())) {
				throw new RuntimeException(serviceResult.getMsgInfo());
			} else {
				throw new BusinessException(serviceResult.getMsgInfo());
			}
		}
		return serviceResult.getData();
	}

	/**
	 * 递归生成树
	 * 
	 * @param treelist
	 * @param data
	 * @return
	 */
	private List<ResourceTree> generateTree(List<ResourceTree> treelist, List<SystemResources> data) {
		for (SystemResources sr : data) {
			ResourceTree tree = new ResourceTree();
			tree.setId(sr.getId());
			tree.setText(sr.getContent());
			if (this.resRoleIds != null && this.resRoleIds.contains(sr.getId()))
				tree.setChecked(true);
			tree.setChildren(generateTree(new ArrayList<ResourceTree>(), getByPid(sr.getId())));
			tree.setState(tree.getChildren().size() > 0 ? "closed" : "open");
			treelist.add(tree);
		}
		return treelist;
	}

	/**
	 * 角色-资源树
	 * 
	 * @param request
	 * @param dataMap
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "roleResTree")
	public @ResponseBody List<ResourceTree> roleResTree(HttpServletRequest request, Map<String, Object> dataMap,
			String roleId) {
		List<ResourceTree> tree = new ArrayList<ResourceTree>();
		ServiceResponse<List<SystemResources>> serviceResult = resourcesService
				.getByPid(Constants.SYSTEM_RESOURCE_ROOT);
		if (!serviceResult.getSuccess()) {
			if (Constants.SERVICE_RESULT_CODE_SYSERROR.equals(serviceResult.getMsgCode())) {
				throw new RuntimeException(serviceResult.getMsgInfo());
			} else {
				throw new BusinessException(serviceResult.getMsgInfo());
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("rolesId", roleId);
		List<SystemResourcesRoles> srrlist = resourcesRolesService.page(map, null).getData();
		for (SystemResourcesRoles sr : srrlist) {
			this.resRoleIds.add(sr.getResourcesId());
		}
		synchronized (token) {
			this.allres = resourcesService.page(new HashMap<String, Object>(), null).getData();
			generateTree(tree, serviceResult.getData());
		}
		return tree;
	}

	private List<SystemResources> getByPid(Integer pid) {
		if (this.allres == null || this.allres.size() < 1)
			return null;
		List<SystemResources> reslist = new ArrayList<SystemResources>();
		for (SystemResources res : this.allres) {
			if (res.getPid().intValue() == pid.intValue())
				reslist.add(res);
		}
		return reslist;
	}

	@RequestMapping(value = "editWin", method = { RequestMethod.GET })
	public String edit(HttpServletRequest request, ModelMap dataMap, Integer id) {
		if (id != null) {
			SystemResources systemResources = resourcesService.getSystemResourcesById(id).getData();
			dataMap.put("obj", systemResources);
		}
		dataMap.put("id", id);
		return "system/editresourceswin";
	}

	/**
	 * 新增/编辑
	 * 
	 * @param request
	 * @param response
	 * @param cate
	 */
	@RequestMapping(value = "doAdd", method = { RequestMethod.POST })
	public @ResponseBody HttpJsonResult<Boolean> doAdd(HttpServletRequest request, HttpServletResponse response,
								  SystemResources systemResources) {
		HttpJsonResult<Boolean> jsonResult = new HttpJsonResult<Boolean>();
		ServiceResponse<Integer> serviceResult = null;
		try {
			if (systemResources.getId() != null && 0 != systemResources.getId()) {
				serviceResult = resourcesService.updateSystemResources(systemResources);
			} else {
				serviceResult = resourcesService.saveSystemResources(systemResources);
			}
			jsonResult.setRows(serviceResult.getData() > 0);
		} catch (Exception e) {
			jsonResult.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return jsonResult;
	}

	/**
	 *  新增资源窗口
	 * @param id
	 * @param request
	 * @param dataMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "addWin")
	public String addWin(Integer id, HttpServletRequest request, Map<String, Object> dataMap) throws Exception {
		dataMap.put("id", id);
		return "system/addWin";
	}

	@RequestMapping(value = "resTree")
	public @ResponseBody List<ResourceTree> resTree(HttpServletRequest request, Map<String, Object> dataMap) {
		List<ResourceTree> tree = new ArrayList<ResourceTree>();
		ServiceResponse<List<SystemResources>> serviceResult = resourcesService.page(new HashMap<String, Object>(),
				null);
		if (!serviceResult.getSuccess()) {
			if (Constants.SERVICE_RESULT_CODE_SYSERROR.equals(serviceResult.getMsgCode())) {
				throw new RuntimeException(serviceResult.getMsgInfo());
			} else {
				throw new BusinessException(serviceResult.getMsgInfo());
			}
		}
		synchronized (token) {
			this.allres = serviceResult.getData();
			generateTree(tree, getByPid(Constants.SYSTEM_RESOURCE_ROOT));
		}
		return tree;
	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @param cate
	 */
	@RequestMapping(value = "del", method = { RequestMethod.GET })
	public @ResponseBody HttpJsonResult<Boolean> del(HttpServletRequest request, HttpServletResponse response,
			Integer id) {
		HttpJsonResult<Boolean> jsonResult = new HttpJsonResult<Boolean>();
		try {
			ServiceResponse<Boolean> serviceResult = resourcesService.del(id);
			if (!serviceResult.getSuccess()) {
				if (Constants.SERVICE_RESULT_CODE_SYSERROR.equals(serviceResult.getMsgCode())) {
					throw new RuntimeException(serviceResult.getMsgInfo());
				} else {
					throw new BusinessException(serviceResult.getMsgInfo());
				}
			}
		} catch (Exception e) {
			jsonResult.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return jsonResult;
	}

}
